const crypto = require('crypto');
const request = require('request');
const config = require('../config');
const appId = config.wx.appId;
const secret = config.wx.secret;;
const baseUrl = `https://api.weixin.qq.com/cgi-bin`;
const appService = require('../service/appService');
const util = require('./util.js');

function createOrderFinashedMessage({openId, orderNo, goods, amount}) {
	batchPush({
		touser: openId,
		template_id: 'YrZg2UV6IqgSMJiDPjKSNYzMHE4lSOIYmTcLl4JEiZo',
		page: 'pages/views/tabBar/home',
		data: {
			'character_string1': {
				value: orderNo
			},
			'phrase2': {
				value: '已完成'
			},
			'time6': {
				value: util.dateFtt('yyyy-MM-dd hh:mm:ss', new Date())
			},
			'thing9': {
				value: generateGoodsName(goods)
			},
			'amount8': {
				value: amount
			},
			'thing5': {
				value: '您的订单已完成，欢迎您再次使用'
			}
		}
	})
}

function createOrderSubmitMessage({openId, orderNo, goods, amount}) {
	console.log(generateGoodsName(goods));
	batchPush({
		touser: openId,
		template_id: 'YrZg2UV6IqgSMJiDPjKSNYzMHE4lSOIYmTcLl4JEiZo',
		page: 'pages/views/tabBar/home',
		data: {
			'character_string1': {
				value: orderNo
			},
			'date2': {
				value: util.dateFtt('yyyy-MM-dd hh:mm:ss', new Date())
			},
			'thing3': {
				value: generateGoodsName(goods)
			},
			'amount4': {
				value: amount
			},
			'thing5': {
				value: '您的订单已被商家确认，正在为您配送中'
			}
		}
	})
}

function generateGoodsName(goods) {
	let goodsName = '';
	goods.forEach(item => goodsName += item.goodsName + ',');
	return '奥克兰奥克兰';//goodsName;
}

async function batchPush(message) {
    const token = await getAccessToken();
    request({
        url: `${baseUrl}/message/subscribe/send?access_token=${token}`,
        method: 'POST',
        headers: {
            'content-type': 'application/json;charset=UTF-8'
        },
        body: JSON.stringify({
            access_token: token,
			...message
        })
    }, function(error, res, body) {
        let data = JSON.parse(body);
		console.log(body);
       if (data.errcode === 0) {
		   console.log('*********************发送成功***********************');
        } else if (data.code === 40001) {
			initAccessToken();
			batchPush(openId, message);
        }
    });
}

async function getAccessToken() {
    const app = await appService.find();
    return app.wxAccessToken;
}

function initAccessToken() {
    return new Promise((resolve, reject) => {
        request({
            url: `${baseUrl}/token?grant_type=client_credential&appid=${appId}&secret=${secret}`,
            method: 'get'
        }, async(error, res, body) => {
            let data = JSON.parse(body);
			console.log(data);
            if (data.errcode) {
				reject();
            } else {
				// 保存token
				await appService.update({
				    wxAccessToken: data.access_token
				})
				console.log('access_token获取完毕');
				resolve();
			}
        });
    })
}

module.exports = {
    initAccessToken,
    batchPush,
	createOrderSubmitMessage,
	createOrderFinashedMessage
}